package com.example.javalib.math;

/**
 * @Description: x平方根的整数部分
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/1/22 11:43
 */
public class SqrtX {
    public static void main(String[] args) {

        int i = binarySearch(26);
        int y = newtonSearch(26);
        System.out.println("平方根的整数部分；" + i);
        System.out.println("平方根的整数部分；" + y);
    }
    //二分法
    public static int binarySearch(int x) {
        int zheng = 0, left = 0, right = x;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (mid * mid <= x) {
                zheng = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return zheng;
    }

    //牛顿 迭代
    public static int newtonSearch(int x) {
       if(x == 0){
           return  0;
       }
       return (int) sqrt(x,x);
    }

    private static double sqrt(double n, int x) {
        double res = (n + x / n) / 2;
        if (res == n) {
            return n;
        }
        return sqrt(res, x);
    }

}
